package com.simplehire.service.impl;

import com.simplehire.model.User;
import com.simplehire.model.UserPermission;
import com.simplehire.repository.UserPermissionRepository;
import com.simplehire.repository.UserRepository;
import com.simplehire.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final UserPermissionRepository permissionRepository;
    private final PasswordEncoder passwordEncoder;

    @Override
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    @Override
    @Transactional
    public User createUser(User user) {
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    @Override
    @Transactional
    public User updateUser(Long id, User user) {
        User existingUser = getUserById(id);
        existingUser.setUsername(user.getUsername());
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            existingUser.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        existingUser.setRole(user.getRole());

        return userRepository.save(existingUser);
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        User user = getUserById(id);
        userRepository.delete(user);
    }

    @Override
    public List<UserPermission> getUserPermissions(Long userId) {
        return permissionRepository.findByUserId(userId);
    }

    @Override
    @Transactional
    public UserPermission addUserPermission(Long userId, String permission, LocalDateTime expiresAt) {
        User user = getUserById(userId);

        UserPermission userPermission = new UserPermission();
        userPermission.setUser(user);
        userPermission.setPermission(permission);
        userPermission.setExpiresAt(expiresAt);

        return permissionRepository.save(userPermission);
    }

    @Override
    @Transactional
    public void removeUserPermission(Long userId, String permission) {
        permissionRepository.deleteByUserIdAndPermission(userId, permission);
    }

    @Override
    @Transactional
    public void removeUserPermissionById(Long userId, Long permissionId) {
        // 首先查找权限，确保它属于指定用户
        Optional<UserPermission> permissionOptional = permissionRepository.findById(permissionId);
        if (permissionOptional.isPresent()) {
            UserPermission permission = permissionOptional.get();
            if (permission.getUser().getId().equals(userId)) {
                permissionRepository.delete(permission);
            } else {
                throw new RuntimeException("权限与用户不匹配");
            }
        } else {
            throw new RuntimeException("权限不存在");
        }
    }

    @Override
    public List<User> searchUsers(String keyword) {
        return userRepository.searchByUsername(keyword);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getRole() == User.Role.ADMIN;
    }
}
